package com.qlylkj.lbk.ui.cochain

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.qlylkj.lbk.base.BaseViewModel
import com.qlylkj.lbk.model.api.ResultResponse
import com.qlylkj.lbk.model.bean.CoChainInfo
import com.qlylkj.lbk.model.repository.CompanyRepository

class CoChainViewModel: BaseViewModel() {

    private val _uiState = MutableLiveData<CoChainUiModel>()
    val uiState: LiveData<CoChainUiModel>
        get() = _uiState

    private val companyRepository by lazy { CompanyRepository() }

    private var offset = 0

    private fun emitUiState(
        showError: String? = null,
        isRefresh: Boolean = true,
        coChainInfoList: MutableList<CoChainInfo> = mutableListOf()
    ) {
        val uiModel = CoChainUiModel(showError, isRefresh, coChainInfoList)
        _uiState.value = uiModel
    }

    data class CoChainUiModel(
        val showError: String?,
        val isRefresh: Boolean,
        val coChainInfoList: MutableList<CoChainInfo>
    )

    fun getCoChainInfoList(userId: String,isRefresh: Boolean){
        if (isRefresh) {
            offset = 1
        } else {
            offset++
        }
        launch {
            val result = companyRepository.getUserCoChainList(userId,offset)
            if (result is ResultResponse.SuccessEntity) {
                emitUiState(coChainInfoList = result.data.records)
            } else if (result is ResultResponse.Error) {
                emitUiState(showError = result.exception.message)
            }
        }
    }
}